#!/usr/bin/python -tt


######### standard library imports ###########################################

import sys
import logging
import logging.config
import os


from optparse import OptionParser


######### project library imports ############################################
import settings

import readcorsika
import absorb_photons
import reflector   

import turnIntoZenit
import photonDetection

scriptpath = os.path.dirname(os.path.realpath(__file__))
logging.config.fileConfig(scriptpath+'/logging.conf')
logger = logging.getLogger('simulation_root')


parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
    help="write report to FILE", metavar="FILE")
parser.add_option("-p", "--plot",
    action="store_true", dest="create_plots", default=False,
    help="create some informative debugging plots")
options, args = parser.parse_args()
if options.filename is None:
    print 'Please submit a filename. "', sys.argv[0],'-h" for help'
    sys.exit(1)


##############################################################################
############# Here everything starts #########################################

thedict = {}

thedict = settings.put_settings_into_dict( thedict )

#------------ start: read the corsika file

thedict = readcorsika.readCorsikaFile( thedict, options.filename )

#------------ absorb / delete some photons

thedict = absorb_photons._absorb_photons( thedict, 
        dictname='photonData',
        absorption_key='wavelength',
        absorption_func_key = 'survival_prob_wavelength')

thedict = turnIntoZenit.turn_photons_into_zenith( thedict, 
        dictname='photonData', 
        pos_key='ground_dir', 
        dir_key='ground_pos',
        new_pos_key='ground_pos_turned', 
        new_dir_key='ground_dir_turned')

thedict = absorb_photons._absorb_photons( thedict, 
        dictname='photonData',
        absorption_key='ground_pos_turned',
        absorption_func_key = 'is_in_inner_circle_checker')

#------------ reflector simulation 

thedict = reflector.findMirrorIntersection( thedict, 
        dictname='photonData', 
        pos_key='ground_pos_turned', 
        dir_key='ground_dir_turned',
        mirror_key='mirrors',
        new_pos_key='pos_on_mirror', 
        new_mirror_id_key='mirror_id', 
        new_time_key='time_to_mirror')

thedict = reflector.reflectOnMirrors( thedict, 
        dictname='photonData', 
        mirror_alignment_point_key='mirror_alignment_point',
        pos_key='pos_on_mirror', 
        dir_key='ground_dir_turned',
        new_angle_key='angle_on_mirror', 
        new_dir_key='dir_on_mirror' )
    

thedict = reflector.findFocalPlaneIntersection( thedict, 
        dictname='photonData', 
        focal_plane_key='focal_plane',
        pos_key='pos_on_mirror', 
        dir_key='dir_on_mirror',
        new_pos_key='pos_in_focal_plane', 
        new_time_key='time_to_focal_plane')
        
thedict = reflector.findPixelChid( thedict, 
        dictname='photonData', 
        focal_plane_key='focal_plane',
        pos_key='pos_in_focal_plane', 
        new_chid_key='chid', 
        new_Coordinator_key='Coordinator', 
        new_pixel_center_key='pixel_center')

#------------  Camera Simulation
thedict = photonDetection.makeEventDict( thedict,
        dictname='eventData')

thedict = photonDetection.addNsbAndDarkNoise( thedict, 
        noiseDictname='PhotonNoiseInfo', 
        outDictname='eventData')

thedict = photonDetection.simulateOpticalCrosstalk( thedict, 
        eventdictname='eventData',
        hitdictnames = ['NoiseHits', 'CherenkovHits'],
        outdictname = 'AllHitsWithWeights')

### Space for the more interesting trigger

#thedict = photonDetection.applyMostSimpleTrigger( thedict, level=4)

thedict = photonDetection.applyTrigger( thedict, coincidenceWindow = 13*1e-9, level=20, keyname='trigger')


#------------ Adc simulation, i.e. rawdata generation

        ## This is the function, which eats most of the time ##
#photonDetection.MakeAndSaveAdcData( thedict, filename=options.filename+'.fits')

logging.info("the end.")    


############# This is the end my friend ######################################
##############################################################################

if options.create_plots:
    readcorsika.make_plots(thedict)
    reflector.make_plots(thedict)


    
    
    
    
    

